package com.lzw.shiro.web;

import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "loginServlet", urlPatterns = "/login")
public class LoginServlet  extends HttpServlet {
	@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
    }

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//如果登录失败从request中获取认证异常信息，shiroLoginFailure就是shiro异常的全限定名
		String exceptionClassName = (String) req.getAttribute("shiroLoginFailure");
		if(exceptionClassName != null){
			if (UnknownAccountException.class.getName().equals(exceptionClassName)){
				//最终会抛给异常处理器
				req.setAttribute("errorMsg","账号不存在");
			}else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)){
				req.setAttribute("errorMsg","用户名/密码错误");
			}else{
				req.setAttribute("errorMsg","其他异常信息");
			}
		}
		//此方法不处理登录成功，shiro认证成功后会自动跳转到上一个请求的页面
		//登录失败还会在login
		req.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(req, resp);
	}
}
